package com.blyat.xsoft.auth.restful.service.impl;

import com.blyat.xsoft.auth.restful.entity.Authority;
import com.blyat.xsoft.auth.restful.entity.Role;
import com.blyat.xsoft.auth.restful.mapper.AuthorityMapper;
import com.blyat.xsoft.auth.restful.mapper.RoleMapper;
import com.blyat.xsoft.kernel.restful.service.CrudService;
import com.blyat.xsoft.auth.restful.service.RoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.stream.Collectors;

/**
 * @author syh
 * @date 2019/10/21
 **/
@Service
public class RoleServiceImpl extends CrudService<Role, RoleMapper> implements RoleService {
    @Autowired
    AuthorityMapper authorityMapper;

    @Override
    public List<Role> getByUserId(String userId) {
        return mapper.getByUserId(userId);
    }

    @Override
    public List<Authority> getAuthByRole(String roleId) {
        return authorityMapper.getAuthByRole(roleId);
    }

    @Override
    public int auth(Role role) {
        mapper.deletePermissionByRoleId(role.getId());
        if (role.getAuthorities() != null && !role.getAuthorities().isEmpty()) {
            mapper.updateRolePermission(role.getId(), role.getAuthorities().stream().map(Authority::getId).collect(Collectors.toList()));
        }
        return super.update(role);
    }

    @Override
    public int deleteByIds(String[] ids) {
        mapper.deletePermissionByRoleIds(ids);
        return super.deleteByIds(ids);
    }
}
